import React, { useState, useCallback } from 'react';
import { Tree, Card, Button, Space, Typography, message } from 'antd';
import { DragOutlined, SaveOutlined, ReloadOutlined } from '@ant-design/icons';
import type { TreeDataNode, TreeProps } from 'antd/es/tree';
import { useTheme } from '../contexts/ThemeContext';

const { Title } = Typography;

interface DragSortItem {
  id: number;
  title: string;
  key: string;
  children?: DragSortItem[];
  [key: string]: any;
}

interface DragSortTreeProps {
  data: DragSortItem[];
  onSave: (sortedData: any[]) => Promise<void>;
  onRefresh: () => void;
  loading?: boolean;
  title?: string;
}

const DragSortTree: React.FC<DragSortTreeProps> = ({
  data,
  onSave,
  onRefresh,
  loading = false,
  title = '拖拽排序'
}) => {
  const { currentTheme } = useTheme();
  const [treeData, setTreeData] = useState<TreeDataNode[]>([]);
  const [hasChanges, setHasChanges] = useState(false);
  const [saving, setSaving] = useState(false);

  // 转换数据格式
  React.useEffect(() => {
    const convertToTreeData = (items: DragSortItem[]): TreeDataNode[] => {
      if (!items || !Array.isArray(items)) return [];

      return items.map((item, index) => {
        // 确保显示文本不为空
        const displayText = item.title || item.display_name || item.name || '未命名';

        // 创建干净的节点对象，避免循环引用
        const node: TreeDataNode = {
          key: item.key || item.id?.toString() || `node-${index}`,
          title: (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <DragOutlined style={{ color: currentTheme.colorTextSecondary }} />
              <span>{displayText}</span>
              <span style={{
                fontSize: '12px',
                color: currentTheme.colorTextTertiary,
                marginLeft: 'auto'
              }}>
                #{index + 1}
              </span>
            </div>
          ),
          // 只保留必要的数据属性，避免循环引用
          id: item.id,
          display_name: item.display_name,
          name: item.name,
          path: item.path,
          sort_order: item.sort_order,
          parent_id: item.parent_id
        };

        // 递归处理子节点
        if (item.children && Array.isArray(item.children) && item.children.length > 0) {
          node.children = convertToTreeData(item.children);
        }

        return node;
      });
    };

    try {
      const treeData = convertToTreeData(data);
      setTreeData(treeData);
      setHasChanges(false);
    } catch (error) {
      setTreeData([]);
      setHasChanges(false);
    }
  }, [data, currentTheme]);

  // 处理拖拽
  const onDrop: TreeProps['onDrop'] = useCallback((info) => {
    const dropKey = info.node.key;
    const dragKey = info.dragNode.key;
    const dropPos = info.node.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

    const loop = (data: TreeDataNode[], key: React.Key, callback: (node: TreeDataNode, i: number, data: TreeDataNode[]) => void) => {
      for (let i = 0; i < data.length; i++) {
        if (data[i].key === key) {
          return callback(data[i], i, data);
        }
        if (data[i].children) {
          loop(data[i].children!, key, callback);
        }
      }
    };

    const data = [...treeData];
    let dragObj: TreeDataNode;

    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) {
      // 拖拽到节点内部
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        item.children.unshift(dragObj);
      });
    } else if (
      ((info.node as any).props.children || []).length > 0 &&
      (info.node as any).props.expanded &&
      dropPosition === 1
    ) {
      // 拖拽到展开节点的第一个位置
      loop(data, dropKey, (item) => {
        item.children = item.children || [];
        item.children.unshift(dragObj);
      });
    } else {
      // 拖拽到节点之间
      let ar: TreeDataNode[] = [];
      let i: number;
      loop(data, dropKey, (_item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i!, 0, dragObj!);
      } else {
        ar.splice(i! + 1, 0, dragObj!);
      }
    }

    setTreeData(data);
    setHasChanges(true);
  }, [treeData]);

  // 保存排序
  const handleSave = async () => {
    if (!hasChanges) {
      message.info('没有需要保存的更改');
      return;
    }

    setSaving(true);
    try {
      // 转换树形数据为扁平的排序数据
      const flattenData = (nodes: TreeDataNode[], parentId: number | null = null, depth: number = 0): any[] => {
        // 防止无限递归
        if (depth > 10) {
          return [];
        }

        const result: any[] = [];
        if (!nodes || !Array.isArray(nodes)) return result;

        nodes.forEach((node, index) => {
          // 确保node.id存在且为数字
          const nodeId = typeof node.id === 'number' ? node.id : parseInt(node.id as string);
          if (isNaN(nodeId)) {
            return;
          }

          result.push({
            id: nodeId,
            sort_order: index,
            parent_id: parentId
          });

          // 递归处理子节点
          if (node.children && Array.isArray(node.children) && node.children.length > 0) {
            const childResults = flattenData(node.children, nodeId, depth + 1);
            result.push(...childResults);
          }
        });
        return result;
      };

      const sortData = flattenData(treeData);

      if (sortData.length === 0) {
        message.warning('没有有效的排序数据');
        return;
      }

      await onSave(sortData);
      setHasChanges(false);
      message.success('排序保存成功');
    } catch (error) {
      message.error('保存排序失败');
    } finally {
      setSaving(false);
    }
  };

  // 重置更改
  const handleReset = () => {
    onRefresh();
    setHasChanges(false);
    message.info('已重置更改');
  };

  return (
    <Card>
      <div style={{ marginBottom: 16 }}>
        <div style={{ 
          display: 'flex', 
          justifyContent: 'space-between', 
          alignItems: 'center',
          marginBottom: 16 
        }}>
          <Title level={5} style={{ margin: 0 }}>
            <DragOutlined style={{ marginRight: 8 }} />
            {title}
          </Title>
          <Space>
            <Button
              icon={<ReloadOutlined />}
              onClick={handleReset}
              disabled={!hasChanges || loading}
            >
              重置
            </Button>
            <Button
              type="primary"
              icon={<SaveOutlined />}
              onClick={handleSave}
              loading={saving}
              disabled={!hasChanges || loading}
            >
              保存排序
            </Button>
          </Space>
        </div>
        
        {hasChanges && (
          <div style={{
            padding: '8px 12px',
            background: 'rgba(255, 193, 7, 0.1)',
            border: '1px solid rgba(255, 193, 7, 0.3)',
            borderRadius: 4,
            fontSize: '12px',
            color: '#d48806'
          }}>
            ⚠️ 您有未保存的排序更改，请记得保存
          </div>
        )}
      </div>

      <Tree
        draggable
        blockNode
        onDrop={onDrop}
        treeData={treeData}
        defaultExpandAll
        showLine={{ showLeafIcon: false }}
        style={{
          background: 'transparent',
          border: `1px solid ${currentTheme.colorBorder}`,
          borderRadius: 6,
          padding: 12
        }}
      />
    </Card>
  );
};

export default DragSortTree;
